//
//  WBRefreshControl.swift
//  SinaWeibo23
//
//  Created by apple on 16/2/23.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SnapKit

enum WBRefrshStatue: Int {
    case Normal = 1   //正常的初始状态
    
    case Pulling = 2  //准备刷新的状态

    case Refreshing = 3 //正在刷新的状态
}


class WBRefreshControl: UIControl {

    
    //声明状态的属性
    var statue: WBRefrshStatue = .Normal {
        didSet {
            //一旦状态被设置  修改视图显示
            switch statue {
            case .Normal:
                tipLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                //停止小菊花的转动
                indicationView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
                
                //恢复 父视图的inset  需要根据上衣的刷新状态来决定是否执行 减 inset.top的操作\
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= self.RefreshHeight
                        self.scrollView?.contentInset = inset

                    })
                }
                
            case .Pulling:
                tipLabel.text = "松开刷新"
                //旋转箭头方向  系统默认的动画时间  0.25
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                tipLabel.text = "正在刷新"
                self.sendActionsForControlEvents(.ValueChanged)
                
                //1.隐藏箭头
                self.arrowIcon.hidden = true
                //2.转动菊花
                self.indicationView.startAnimating()
                
                //修改父视图的contentInset
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top += self.RefreshHeight
                    self.scrollView?.contentInset = inset
                    
                })
            }

        }
    }

    private let RefreshHeight: CGFloat = 60
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshHeight, width: ScreenWidth, height: RefreshHeight)
        super.init(frame: rect)
//        backgroundColor = UIColor.yellowColor()
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func endRefreshing() {
        
        //延时执行
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.3))
        dispatch_after(time_t, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    }
    
    //KVO观察响应方法
    //实时获取父视图的位移  根据位移  和 '临界值' 来进行对比
    //需要实时的修改刷新的状态  1.正常的状态  2. 等待刷新状态  3.正在刷新的状态
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        printLog(change)
        //1. 获取tableView的 在 垂直方向的位移
        let offsetY = scrollView?.contentOffset.y ?? 0
        
        //临界值 是 -124
        let conaditionValue = -(RefreshHeight + (scrollView?.contentInset.top ?? 0))
        if scrollView!.dragging {
            //正在被拽动
            //将状态的判断卸载前面 可以提高判断的效率
            if  statue == .Normal && conaditionValue > offsetY {
                // 等待刷新的状态
                printLog("等待刷新状态")
                statue = .Pulling
                
            } else if statue == .Pulling && conaditionValue < offsetY {
                //普通状态
                printLog("普通状态")
                statue = .Normal
            }
            
        } else {
            
            //松手 && 满足 准备刷新的状态  -> 正在刷新状态
            //只有准备刷新的状态才能进入到 正在刷新状态
            if statue == .Pulling {
                printLog("正在刷新")
                statue = .Refreshing
            }
            
        }
    }
    
    
    //如何获取 拖拽tableView时 产生的位移  如何在刷新控件中获取tableVie
    //重写UIView 生命周期方法
    //将要被添加到父视图上面
    override func willMoveToSuperview(newSuperview: UIView?) {
        //调用super
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView {
            //需要判断下拉刷新控件的父视图是否是 UIScrollView 及其子类
            //这个控件 可以提供 scrollView tableView collectionView 来进行下拉刷新使用
            //将父视图记录下来
            //            printLog("是scrollView")
            scrollView = myFather
            //观察父视图的contentOffset 这个属性
            //实时观察对象的属性的变化
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    //移除观察者
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    private func setupUI() {
        
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
        backImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
        }
       
        //设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
    }
    
    var scrollView: UIScrollView?
    
    //MARK: 懒加载子视图
    private lazy var tipLabel: UILabel = UILabel(text: "下拉刷新", fontSize: 14, textColor: UIColor.darkGrayColor())
    
    //箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //小菊花
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))

}
